package com.cmcc.groupcontacts.firewall.business;

import java.util.ArrayList;

import android.database.Cursor;
import android.provider.CallLog;
import android.provider.ContactsContract;

import com.cmcc.groupcontacts.MainApp;
import com.cmcc.groupcontacts.firewall.dao.CallListDAO;
import com.cmcc.groupcontacts.firewall.dao.model.CallListVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.StringUtil;
import com.cmcc.groupcontacts.util.ValidationUtil;

/**
 * 来电拦截记录业务处理类
 * 
 * @author 
 * 
 */
public class CallListBusiness extends BaseBusiness {
	private CallListDAO callListDAO;

	public CallListBusiness() {
		super();

		callListDAO = new CallListDAO();
	}

	/**
	 * 处理被拦截的来电：<br />
	 * 从系统通话记录中删除被拦截的来电，并将被拦截的来电插入来电拦截记录。
	 */
	public void handleBlockedCall() {
		Cursor cursor = null;
		String[] projection = new String[] { CallLog.Calls._ID, CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.DATE, CallLog.Calls.TYPE };
		String where = StringUtil.format("{0}>{1} AND PHONE_NUMBERS_EQUAL({2},'{3}',0)", CallLog.Calls.DATE, (System.currentTimeMillis() - 10000L),
				CallLog.Calls.NUMBER, MainApp.blockedNumber); // 不能判断Duration=0，因为例如米UI中就对挂断的电话计算了时长的
		try {
			cursor = cr.query(CallLog.Calls.CONTENT_URI, projection, where, null, CallLog.Calls.DEFAULT_SORT_ORDER);
			if (cursor != null && cursor.moveToPosition(0)) {
				// 将被拦截的来电插入来电拦截记录
				CallListVO callList = new CallListVO();
				int callLogId = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
				callList.setNumber(cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
				callList.setDate(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));
				callList.setType(MainApp.blockedType);
				String contactsName = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
				if (ValidationUtil.isNullOrEmpty(contactsName)) {
					contactsName = getContactsName();
				}
				callList.setName(contactsName);
				long callListId = callListDAO.add(callList);
				// 从系统通话记录中删除被拦截的来电，如果失败就同时从来电拦截记录中删除
				boolean isDeleteFailed = false;
				try {
					isDeleteFailed = (deleteCallLog(callLogId) <= 0);
				} catch (Exception e) {
					isDeleteFailed = true;
					ExceptionHandler.handle(e, "从系统通话记录中删除被拦截的来电时出错");
				} finally {
					if (isDeleteFailed) {
						callListDAO.del(CallListVO.MetaData.ID + "=" + callListId, null);
					}
					// TODO: 只保留100条拦截记录
				}
			}
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
			MainApp.blockedNumber = null;
		}
	}

	/*
	 * 获取联系人姓名
	 */
	private String getContactsName() {
		Cursor cursor = null;
		String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };
		String where = StringUtil.format("PHONE_NUMBERS_EQUAL({0},'{1}',0)", ContactsContract.CommonDataKinds.Phone.NUMBER, MainApp.blockedNumber);
		try {
			cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, where, null, null);
			if (cursor != null && cursor.moveToPosition(0)) {
				return cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			} else {
				return null;
			}
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
	}

	/**
	 * 获取所有来电拦截记录
	 * 
	 * @return
	 */
	public ArrayList<CallListVO> getCallList() {
		String orderBy = CallListVO.MetaData.DATE + " desc";
		return callListDAO.query(false, CallListVO.MetaData.ALL_COLS, null, null, null, null, orderBy, null);
	}

	/**
	 * 删除通话记录
	 * 
	 * @param id
	 * @return
	 */
	public int deleteCallLog(int id) {
		return cr.delete(CallLog.Calls.CONTENT_URI, CallLog.Calls._ID + "=" + id, null);
	}

	/**
	 * 删除通话记录
	 * 
	 * @param number
	 * @return
	 */
	public int deleteCallLog(String number) {
		return cr.delete(CallLog.Calls.CONTENT_URI, "PHONE_NUMBERS_EQUAL(" + CallLog.Calls.NUMBER + " , '" + number + "',0)", null);
	}

	/**
	 * 删除来电拦截记录
	 * 
	 * @param id
	 * @return
	 */
	public long delete(int id) {
		return callListDAO.del(CallListVO.MetaData.ID + "=" + id, null);
	}
}
